/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2023-10-09 16:46:01
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2023-11-23 17:39:04
 * @FilePath: /logsystem/logs/util.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*实用工具类的实现：
    1. 获取系统时间
    2. 判断文件是否存在
    3. 获取文件所在路径
    4. 创建目录
*/
#ifndef __M_UTIL_H__
#define __M_UTIL_H__
#include <iostream>
#include <ctime>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

namespace zbtlog
{
    namespace util
    {
        class Date
        {
            public:
                static size_t now()
                {
                    return (size_t)time(nullptr);
                }
        };
        class File
        {
        public:
            static bool exists(const std::string &pathname)
            {
                struct stat st;
                if (stat(pathname.c_str(), &st) < 0)
                {
                    return false;
                }
                return true;
            }
            static std::string path(const std::string &pathname)
            {
                size_t pos = pathname.find_last_of("/\\");
                // 没找到就返回当前目录
                if (pos == std::string::npos) return ".";
                // 找到了就返回目标路径
                return pathname.substr(0, pos + 1);
            }
            static void createDirectory(const std::string &pathname)
            {
                // idx标定起始位置,pos为目标位置
                size_t pos = 0, idx = 0;

                while (idx < pathname.size())
                {
                    pos = pathname.find_first_of("/\\", idx);
                    if (pos == std::string::npos)
                    {
                        mkdir(pathname.c_str(), 0777);
                    }

                    std::string parent_dir = pathname.substr(0, pos + 1);
                    if (exists(parent_dir) == true)
                    {
                        idx = pos + 1;
                        continue;
                    }
                    mkdir(parent_dir.c_str(), 0777);
                    idx = pos + 1;
                        
                }
            }
        };
    }
}

#endif